package com.sptpc.learnspring.service;

import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.repository.CategoryRepository;
import com.sptpc.learnspring.repository.DrinkRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class DrinkService {

    @Autowired
    private DrinkRepository drinkRepository;
    @Autowired
    private CategoryRepository categoryRepository;

    public Drink saveDrink(Drink drink) {

        return drinkRepository.save(drink);
    }

    public List<Drink> getAllDrinks(Long catagoryId){

        return drinkRepository.getDrinksByCategory_Id(catagoryId);
    }

    public Page<Drink> getAll(Pageable pageable) {

        return drinkRepository.findAll(pageable);
    }

    public Drink getDrink(String name) {

        Optional<Drink> drink = drinkRepository.getDrinkByNameLike(name);
        return drink.orElse(null);
    }

    public Drink updateDrink(Drink drink) {

        return drinkRepository.saveAndFlush(drink);
    }

    public void delete(Drink drink) {

        drinkRepository.delete(drink);
    }

    public Drink saveDrink(NewDrinkRequest drinkRequest) {

        Optional<Category> category = categoryRepository.findById(drinkRequest.getCategoryId());
        if (category.isPresent()){
            Drink drink = new Drink();
            BeanUtils.copyProperties(drinkRequest, drink);
            drink.setCategory(category.get());
            return drinkRepository.save(drink);
        }
        return null;
    }

    @Transactional
    public List<Drink> batchSave(List<NewDrinkRequest> drinkRequests) {

        List<Drink> drinks = new ArrayList<>();
        for (NewDrinkRequest request: drinkRequests){
            drinks.add(this.saveDrink(request));
        }
        return drinks;
    }

    public Drink getDrinkById(Long drinkId) {

        Optional<Drink> drink = drinkRepository.getDrinkById(drinkId);
        return drink.orElse(null);
    }
}
